package com.furentech.iotserver.fa.sinopec;

public class SinopecCRCUtil {


    /**


     uint16_t CommFunc_CalCRC( uint8_t *pData,uint16_t Size)
     {
     uint8_t BitCount;
     uint16_t crc;

     crc= 0;
     for ( ;Size > 0 ; Size--)
     {
     crc ^= *pData;
     for (BitCount = 0;BitCount < 8; BitCount++)
     {
     if ( (crc &0x01) == 0x01)
     {
     crc = (crc>>1)^0XA001;
     }
     else
     {
     crc >>= 1;
     }
     }
     pData++;
     }

     return crc;

     }



     */

    public static int calcCrc16WithAddr(int destiAddr, int sourceAddr, byte[] pData, int offset, int length)
    {
        int BitCount;
        int crc;

        crc= 0;


        crc ^= destiAddr&0x00ff;
        for (BitCount = 0;BitCount < 8; BitCount++)
        {
            if ( (crc &0x01) == 0x01)
            {
                crc = (crc>>1)^0XA001;
            }
            else
            {
                crc >>= 1;
            }
        }

        crc ^=sourceAddr&0x00ff;
        for (BitCount = 0;BitCount < 8; BitCount++)
        {
            if ( (crc &0x01) == 0x01)
            {
                crc = (crc>>1)^0XA001;
            }
            else
            {
                crc >>= 1;
            }
        }


        for ( int i=offset;i<(length+offset);i++)
        {
            crc ^= pData[i]&0x00ff;
            for (BitCount = 0;BitCount < 8; BitCount++)
            {
                if ( (crc &0x01) == 0x01)
                {
                    crc = (crc>>1)^0XA001;
                }
                else
                {
                    crc >>= 1;
                }
            }
        }
        return crc&0xffff;
    }


    public static int calcCrc16( byte[] pData, int offset, int length)
    {
        int BitCount;
        int crc;

        crc= 0;

        for ( int i=offset;i<length;i++)
        {
            crc ^= pData[i];
            for (BitCount = 0;BitCount < 8; BitCount++)
            {
                if ( (crc &0x01) == 0x01)
                {
                    crc = (crc>>1)^0XA001;
                }
                else
                {
                    crc >>= 1;
                }
            }
        }
        return crc&0xffff;
    }
}
